package homework1_3;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端
 *
 */
public class ClientClass {
    private String user;//客户端标识
    private PrintStream ps= null;
    private BufferedReader br = null;
    private Scanner sc = null;
    private String str ;
    public ClientClass(String user,Socket socket){
        try {
            this.user = user;
            ps = new PrintStream(socket.getOutputStream());//打印流
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));//输入流
            sc = new Scanner(System.in);//保证一直处于可输入状态
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //发送消息线程
    public Thread send(){
        Thread threadSend = new Thread(){
            @Override
            public void run() {
                while (true){
                    str= sc.next();//获取键盘输入信息
                    ps.println(user+":"+str);//将用户名和输入信息一起发送给服务器
                    ps.flush();
                    if ("bye".equalsIgnoreCase(str)){
                        System.out.println("退出聊天室");
                        break;
                    }

                }
            }


        };
        return threadSend;
    }
    //接收消息线程
    public Thread receive(){
        Thread threadReceive = new Thread(){
            @Override
            public void run() {
                while (true){

                    String s = null;//读取服务器传来的消息
                    try {
                        s = br.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //进行消息拆分
                    String[] strings = null;
                    try {
                        strings = s.split(":");//以：作为拆分点
                    }catch (Exception e){
                        break;
                    }


                    if (user.equalsIgnoreCase(strings[0])){
                        System.out.println("我："+strings[1]);//如果是本人发送的消息，此客户端界面显示我：+消息
                        continue;
                    }
                    System.out.println(strings[0]+":"+strings[1]);//否则显示user+消息
                    if ("bye".equalsIgnoreCase(strings[1])){
                        break;//如果服务端传来的时bye 则跳出循环
                    }
                }



            }


        };
        return threadReceive;
    }
    //关闭流
    public void close(){
        if (null!=null){
            sc.close();
        }
        if (null!=br){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null!=ps){
            ps.close();
        }
    }
}

